<script setup>
import { ref, reactive, getCurrentInstance, onMounted, nextTick } from "vue";
import { onShow } from "@dcloudio/uni-app";
import loading from "@/components/loading/loading.vue";
import { useNoticeStore } from "@/store/notice";
import { useMyToastStore } from "@/store/myToast";
const myToast = useMyToastStore();
const notice = useNoticeStore();
const request = getCurrentInstance()?.proxy?.$request;
const instance = getCurrentInstance();

let showPage = ref(false);
let userInfo = uni.getStorageSync("userInfo") || {};
let page = ref(1);
let noticeType = ref(1);
let noticeList = reactive([]);
let status = ref("loadmore"); //loadmore / loading / nomore
let isMore = ref(true);
let storageNoticeList = notice.data || [];

onShow(() => {
  userInfo = uni.getStorageSync("userInfo") || {};
  page.value = 1;
});

const getNoticeList = async () => {
  try {
    const result = await request.post("noticeList", {
      cookie: userInfo.cookie,
      page: page.value,
      type: noticeType.value,
    });
    // 获取近7天
    let todayDate = new Date();
    result.data.items.forEach((item) => {
      let noticeDate = new Date(item.cjsj.replaceAll("-", "/"));
      let day = parseInt((todayDate - noticeDate) / (1000 * 60 * 60 * 24));
      if (day < 7) {
        item.isLately = true;
      }
      item.xxnr = item.xxnr.split(":");
    });
    console.log(result.data.items);
    // 添加到列表
    noticeList.push(...result.data.items);
    showPage.value = true;
    tabsDisabled.value = false;
    isLoading.value = false;
    if (result.data.items.length > 0 && result.data.items.length == 15) {
      status.value = "loading";
    } else {
      status.value = "nomore";
      isMore.value = false;
    }
  } catch (error) {
    console.log(error);
    myToast.params = {
      type: "error",
      message: "消息列表获取失败",
    };
    isLoading.value = false;
    tabsDisabled.value = false;
    showPage.value = true;
  }
};

if (storageNoticeList.length > 0) {
  noticeList.push(...storageNoticeList);
  showPage.value = true;
} else {
  getNoticeList();
}

uni.$once("updateLoginInfo", () => {
  userInfo = uni.getStorageSync("userInfo") || {};
  getNoticeList();
});
let isLoading = ref(false);
const handleScrolltolower = () => {
  if (isMore.value && !isLoading.value) {
    isLoading.value = true;
    status.value = "loading";
    page.value += 1;
    getNoticeList();
  }
};
// 页面滚动
let scrollViewTop = ref(0);
let oldScrollViewTop = ref(0);
const handleViewScroll = ({ detail }) => {
  oldScrollViewTop.value = detail.scrollTop;
};
const backTop = () => {
  scrollViewTop.value = oldScrollViewTop.value;
  nextTick(() => {
    scrollViewTop.value = 0;
  });
};
// 获取高度
let headerHeight = ref(0);
let tabsHeight = ref(0);
onMounted(() => {
  setTimeout(() => {
    const query = uni.createSelectorQuery().in(instance);
    query
      .select(".header-navbar")
      .boundingClientRect((data) => {
        headerHeight.value = data.height;
      })
      .exec();
    const tabs = uni.createSelectorQuery().in(instance);
    tabs
      .select(".tabs-box")
      .boundingClientRect((data) => {
        tabsHeight.value = data.height;
      })
      .exec();
  }, 300);
});

// 切换已读未读
let tabsDisabled = ref(false);
const handleTabsClick = ({ index }) => {
  if (!tabsDisabled.value) {
    tabsDisabled.value = true;
    delIndex.length = 0;
    noticeType.value = index + 1;
    page.value = 1;
    noticeList.length = 0;
    isMore.value = true;
    backTop();
    getNoticeList();
  }
};
// read
let windowHeight = 0;
uni.getSystemInfo({
  success: (res) => {
    windowHeight = res.windowHeight;
  },
});
let itemIndex = ref(null);
let showMask = ref(false);
let isScroll = ref(true);
const handleNoticeItemClick = (index) => {
  if (noticeType.value === 2) {
    return;
  }
  scrollViewTop.value = oldScrollViewTop.value;
  itemIndex.value = index;
  showMask.value = true;
  const el = uni.createSelectorQuery().in(instance);
  el.select(`#notice-item${index}`)
    .boundingClientRect((data) => {
      let top = data.top - (headerHeight.value + tabsHeight.value);
      let bottom = windowHeight - data.bottom;
      if (bottom < 88) {
        scrollViewTop.value = oldScrollViewTop.value - bottom + 88;
      }
      if (top < 15) {
        scrollViewTop.value = oldScrollViewTop.value + top - 15;
      }
      isScroll.value = false;
    })
    .exec();
};
const handleMaskClick = () => {
  showMask.value = false;
  isScroll.value = true;
};

// 请求已读
let isRead = ref(false);
let delIndex = reactive([]);
const readNoticeItem = async (item, index) => {
  isRead.value = true;
  try {
    const result = await request.post("readNotice", {
      cookie: userInfo.cookie,
      id: item.zjxx,
    });
    console.log(result);
    if (result.data.includes("成功")) {
      myToast.params = {
        type: "success",
        message: "操作成功",
      };
      delIndex.push(index);
      handleMaskClick();
      isRead.value = false;
      notice.isNext = true;
    } else {
      myToast.params = {
        type: "error",
        message: "操作失败，请刷新后重试",
      };
      isRead.value = false;
      notice.isNext = true;
    }
  } catch (error) {
    isRead.value = false;
    myToast.params = {
      type: "error",
      message: "操作失败，请稍后重试",
    };
    console.log(error);
  }
};
</script>

<template>
  <view class="notice-list">
    <myToast></myToast>
    <loading v-if="!showPage"></loading>
    <view class="header-navbar">
      <u-navbar autoBack placeholder leftIconSize="38">
        <template #center>
          <text class="text-16 text-bold-700">消息列表</text>
        </template>
      </u-navbar>
    </view>
    <view class="tabs-box" :style="{ top: `${headerHeight}px` }">
      <u-tabs
        :list="[
          {
            name: '未读消息',
            disabled: tabsDisabled,
          },
          {
            name: '已读消息',
            disabled: tabsDisabled,
          },
        ]"
        lineColor="#109363"
        lineHeight="6"
        lineWidth="68"
        :activeStyle="{ color: '#303133' }"
        :inactiveStyle="{ color: '#777' }"
        @click="handleTabsClick"
      ></u-tabs>
    </view>
    <scroll-view
      :style="{
        height: `${windowHeight - (tabsHeight + headerHeight)}px`,
      }"
      :show-scrollbar="true"
      :scroll-y="isScroll"
      :scroll-top="scrollViewTop"
      :scroll-with-animation="true"
      @scrolltolower="handleScrolltolower"
      @scroll="handleViewScroll"
      ><view class="notice-tips"
        >首页会显示近7天的未读消息，请及时刷新课表</view
      >
      <view class="skeleton-box" catchtouchmove="ture" v-if="tabsDisabled">
        <view class="skeleton-item" v-for="item in 5">
          <u-skeleton
            rows="4"
            title
            loading
            titleHeight="36"
            :rowsWidth="['calc(100%)', 'calc(100%)', '140%', '80%']"
            rowsHeight="32"
          ></u-skeleton>
        </view>
      </view>
      <view class="notice-content" v-else>
        <u-transition
          :show="!delIndex.includes(index)"
          mode="fade-right"
          v-for="(item, index) in noticeList"
          :key="index"
        >
          <view
            class="notice-item"
            :id="`notice-item${index}`"
            @longpress="handleNoticeItemClick(index)"
            :style="{ zIndex: index == itemIndex && showMask ? '12' : '0' }"
          >
            <view class="notice-title flex align-center justify-between">
              <text
                >{{ item.xxnr[0] }}{{ item.xxnr.length > 1 ? "：" : "" }}
              </text>
              <view class="tag-box" v-if="item.isLately"> 近7天 </view>
            </view>
            <view class="notice-text">{{ item.xxnr[1] }}</view>
            <view class="time-box">{{ item.cjsj }}</view>
            <view
              class="submit-btn"
              :class="index == itemIndex && showMask ? 'submit-btn-show' : ''"
              @click.stop
            >
              <u-button
                color="#109363"
                text="已读"
                shape="circle"
                throttleTime="1000"
                :disabled="isRead"
                :loading="isRead"
                @click.stop="readNoticeItem(item, index)"
              ></u-button>
            </view> </view
        ></u-transition>
        <view class="null-box" v-if="noticeList.length == 0">
          <image src="/static/tongzhi.png" mode="widthFix" />
          <text>消息列表为空</text>
        </view>
        <view class="loadmore-box" v-else>
          <u-loadmore
            :status="status"
            loadingIcon="circle"
            iconSize="28"
            fontSize="28"
            nomoreText="- 已经到底了 -"
          />
        </view>
      </view>
    </scroll-view>
    <view
      class="mask-box"
      :style="{ top: `${headerHeight}px` }"
      v-if="!isScroll"
      @click="handleMaskClick"
    ></view>
    <view
      class="go-back flex align-center justify-center"
      v-show="oldScrollViewTop > 300 ? true : false"
      @click="backTop"
    >
      <u-icon
        class="back-icon"
        name="arrow-up"
        color="#969EAC"
        size="36"
      ></u-icon>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f9f9f9;
}
.notice-list {
  .tabs-box {
    position: sticky;
    left: 0;
    right: 0;
    z-index: 9;
    background-color: #fff;
    border-bottom: 1px solid #f1f3f5;
    :deep(.u-tabs) {
      .u-tabs__wrapper__nav__item {
        flex: 1;
      }
      .u-tabs__wrapper__nav__line {
        margin-left: 16px;
        bottom: 4px !important;
      }
      .u-tabs__wrapper__nav__item__text {
        font-weight: 700 !important;
      }
    }
  }
  .notice-tips {
    font-size: 26rpx;
    color: #aaa;
    text-align: center;
    padding-top: 24rpx;
  }
  .skeleton-box {
    padding: 28rpx;
    .skeleton-item {
      padding: 28rpx 32rpx;
      margin-bottom: 32rpx;
      background-color: #fff;
      border-radius: 24rpx;
      box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.14);
    }
    :deep(.u-skeleton) {
      .u-skeleton__wrapper__content__title {
        margin-bottom: 12rpx;
      }
      .u-skeleton__wrapper__content__rows {
        margin-top: 20rpx !important;
        &:last-child {
          margin-top: 24rpx !important;
          height: 28rpx !important;
        }
      }
    }
  }
  .notice-content {
    padding: 28rpx;
    position: relative;
    .notice-item {
      position: sticky;
      padding: 28rpx 32rpx;
      margin-bottom: 32rpx;
      background-color: #fff;
      border-radius: 24rpx;
      box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.14);
      font-size: 28rpx;
      color: #109363;
      .notice-title {
        font-size: 30rpx;
        font-weight: 700;
        .tag-box {
          font-size: 12px;
          padding: 2rpx 12rpx;
          background-color: #ff9900;
          color: #fff;
          border-radius: 8rpx;
        }
      }
      .notice-text {
        margin-top: 12rpx;
        color: #000;
      }
      .time-box {
        color: #aaa;
        margin-top: 20rpx;
      }
    }
    .null-box {
      padding: 188rpx;
      text-align: center;
      color: #aaa;
      image {
        height: auto;
      }
    }
    .loadmore-box {
      padding: 8rpx 0 28rpx;
    }
  }
  .submit-btn {
    max-height: 0;
    background-color: #fff;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    will-change: max-height;
    :deep(.u-button) {
      margin: 32rpx 0 8rpx;
    }
  }
  .submit-btn-show {
    max-height: 120rpx;
  }
  .mask-box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 11;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(8px);
  }
  .go-back {
    width: 88rpx;
    height: 88rpx;
    position: fixed;
    bottom: 88rpx;
    right: 58rpx;
    background-color: #e1e1e1ee;
    border-radius: 50%;
    color: #606266;
  }
  :deep(.u-picker__view) {
    height: 488rpx !important;
    .u-picker__view__column__item {
      line-height: 34px !important;
    }
  }
}
</style>
